package org.ws.httphelper.support.pipeline.handler.response;

import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.ws.httphelper.core.pipeline.HandlerOrder;
import org.ws.httphelper.core.pipeline.ResponseHandler;
import org.ws.httphelper.exception.ResponseException;
import org.ws.httphelper.model.RequestContext;
import org.ws.httphelper.model.http.ResponseData;
import org.ws.httphelper.model.http.ResponseFuture;

import java.util.Map;

@HandlerOrder(1)
public class ParseRedirectUrlHandler implements ResponseHandler {

    @Override
    public boolean handler(RequestContext requestContext) throws ResponseException {
        ResponseFuture responseFuture = requestContext.getResponseFuture();
        if(responseFuture.isSuccess()){
            ResponseData response = responseFuture.getResponse();
            if(response.getStatus() == 302){
                Map<String, String> headers = response.getHeaders();
                if(MapUtils.isNotEmpty(headers)){
                    String location = String.valueOf(headers.get("location"));
                    if(StringUtils.isNotBlank(location)){
                        responseFuture.setOutput(location);
                    }
                }
            }
        }
        return true;
    }
}
